import { expandGlob } from "https://deno.land/std@0.88.0/fs/mod.ts";
import { convert } from "https://deno.land/x/deno_webp_converter@0.0.2/mod.ts";
import { lodash } from "https://deno.land/x/deno_ts_lodash@0.0.1/mod.ts";
import { Semaphore } from "https://deno.land/x/async@v2.0.2/mod.ts";

const semaphore = new Semaphore(4); // 并发数
const workers: Promise<any>[] = [];

async function convertWorker(path: string) {
  await semaphore.lock(async () => {
    const newPath = path
      .replace(
        /[_a-z\s]*(\d+)[_a-z\s]*(\.jpg|\.jpeg|\.png)$/i,
        function ($0, $1) {
          const newNumber = lodash.padStart($1, 3, "0");
          return $0.replace($1, newNumber);
        },
      )
      .replace(/\.jpg|\.jpeg|\.png$/i, ".webp");
    console.log("RENAME", path, newPath);
    await convert(path, newPath, "-q 80");
    console.log(`转换成功！删除原文件：${path}`);
    Deno.removeSync(path);
  });
}

for await (const file of expandGlob("./input/**/*.{jpg,jpeg,png,JPG,PNG}")) {
  workers.push(convertWorker(file.path));
}
await Promise.all(workers);
